package com.cam.test.io.web;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/test/io")
public class IOTestController {

    @GetMapping("/fileResponse")
    public ResponseEntity<byte[]> fileResponse(HttpServletResponse response) throws Exception {
        FileInputStream inputStream = new FileInputStream("C:/Users/Tourist/Downloads/ChMkK2Ihce6IOHS4AC1jVKAq-r8AABMHQGdWCgALWNs640.jpg");
//        FileInputStream inputStream = new FileInputStream("D:/Users/Windows/Downloads/ChMkKmHnsCCIPKLzACmH2dzA4wYAAXvOQBF5_wAKYfx089.jpg");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", "test.jpg"));

        /*ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] byteBuffer = new byte[8192];
        while (inputStream.read(byteBuffer) > -1) {
            outputStream.write(byteBuffer);
        }*/

        /*byte[] byteArray = new byte[inputStream.available()];
        int n = 0;
        while (n != -1) {
            n = inputStream.read(byteArray);
        }*/

        byte[] byteArray = new byte[inputStream.available()];
        inputStream.read(byteArray);
        inputStream.close();

        return ResponseEntity.ok().headers(headers).contentType(MediaType.IMAGE_JPEG).body(byteArray);
    }

    @GetMapping("/zipResponse")
    public ResponseEntity<byte[]> zipResponse() throws Exception {
//        FileInputStream inputStream = new FileInputStream("C:/Users/Tourist/Downloads/ChMkK2Ihce6IOHS4AC1jVKAq-r8AABMHQGdWCgALWNs640.jpg");
                FileInputStream inputStream = new FileInputStream("D:/Users/Windows/Downloads/ChMkKmHnsCCIPKLzACmH2dzA4wYAAXvOQBF5_wAKYfx089.jpg");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        zipOutputStream.putNextEntry(new ZipEntry("test.jpg"));
        byte[] byteBuffer = new byte[8192];
        while (inputStream.read(byteBuffer) != -1) {
            zipOutputStream.write(byteBuffer);
        }
        zipOutputStream.flush();
        zipOutputStream.close();
        inputStream.close();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", "test.zip"));

        return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(outputStream.toByteArray());
    }

}
